﻿using ContactSMS.Commons.QueryParameters;
using ContactSMS.Commons.Util;
using ContactSMS.Domain;
using ContactSMS.Domain.Entity;
using ContactSMS.Domain.PagedResult;
using ContactSMS.Infrastructure.dbContexts;
using Microsoft.EntityFrameworkCore;

namespace ContactSMS.Infrastructure
{
    public class MessageSessionRepository : IMessageSessionRepository
    {
        private readonly ContactDbContexts _contactDbContexts;

        public MessageSessionRepository(ContactDbContexts contactDbContexts)
        {
            this._contactDbContexts = contactDbContexts;
        }

        public async Task<MessageSession?> AddMessageSessionAsync(MessageSession messageSession)
        {
            await _contactDbContexts.MessageSessions.AddAsync(messageSession);
            await _contactDbContexts.SaveChangesAsync();
            return messageSession;
        }

        public async Task<bool> DeleteMessageSessionByIdAsync(long id)
        {
            var existing = await _contactDbContexts.MessageSessions.FirstOrDefaultAsync(x => x.Id == id);
            if (existing == null)
            {
                return false;
            }
            _contactDbContexts.MessageSessions.Remove(existing);
            await _contactDbContexts.SaveChangesAsync();
            return true;
        }

        public async Task<bool> DeleteMessageSessionByIdsAsync(long[] ids)
        {
            var messageToDelete = await _contactDbContexts.MessageSessions
                                    .Where(message => ids.Contains(message.Id))
                                    .ToListAsync();
            _contactDbContexts.MessageSessions.RemoveRange(messageToDelete);
            await _contactDbContexts.SaveChangesAsync();
            return messageToDelete == null ? false : true;
        }

        public async Task<MessageSession?> GetMessageSessionByIdAsync(long id)
        {
            return await _contactDbContexts.MessageSessions.FirstOrDefaultAsync(x => x.Id == id);
        }

        public async Task<MessageSession?> GetMessageSessionByMobileAsync(string mobile)
        {
            return await _contactDbContexts.MessageSessions.FirstOrDefaultAsync(x => x.Mobile == mobile);
        }

        public async Task<PagedMessageSessionsResult> GetMessageSessionsAsync(MessageSessionQueryParameters parameters, int page = 1, int pageSize = 10, long userId = 0)
        {
            var query = _contactDbContexts.MessageSessions.AsQueryable();
            if (userId > 0)
            {
                query = query.Where(c => c.UserId.Equals(userId));
            }
            // 筛选条件
            if (!string.IsNullOrEmpty(parameters.SearchTerm))
            {
                query = query.Where(c => c.Mobile.Contains(parameters.SearchTerm) || c.Desc.Contains(parameters.SearchTerm));
            }
            if (!string.IsNullOrEmpty(parameters.Mobile))
            {
                query = query.Where(c => c.Mobile.Equals(parameters.Mobile));
            }
            // 排序方式
            if (!string.IsNullOrEmpty(parameters.SortBy))
            {
                query = ApplySorting(query, parameters.SortBy, parameters.SortDescending);
            }
            // 获取总记录数
            var totalCount = await query.CountAsync();
            // 计算总页数
            var totalPages = (int)Math.Ceiling((double)totalCount / pageSize);

            // 分页查询
            var result = await query
                .Skip((page - 1) * pageSize)
                .Take(pageSize)
                .ToListAsync();
            return new PagedMessageSessionsResult
            {
                MessageSessions = result,
                CurrentPage = page,
                TotalPages = totalPages,
            };
        }

        public async Task<MessageSession?> UpdateMessageSessionAsync(long id, MessageSession messageSession)
        {
            var existing = await _contactDbContexts.MessageSessions.FirstOrDefaultAsync(x => x.Id == id);
            if (existing == null)
            {
                return null;
            }
            existing.Desc = messageSession.Desc;
            existing.SendTime = messageSession.SendTime;
            existing.UpdateTime = TimeUtil.GetTimestamp();
            await _contactDbContexts.SaveChangesAsync();
            return existing;
        }

        private IQueryable<MessageSession> ApplySorting(IQueryable<MessageSession> query, string sortBy, bool sortDescending)
        {
            // 根据排序字段和排序方向对查询进行排序
            switch (sortBy.ToLower())
            {
                case "sendtime":
                    query = sortDescending ? query.OrderByDescending(c => c.SendTime) : query.OrderBy(c => c.SendTime);
                    break;
                // 可以根据需要添加更多的排序字段
                default:
                    // 默认按照 ID 排序
                    query = sortDescending ? query.OrderByDescending(c => c.Id) : query.OrderBy(c => c.Id);
                    break;
            }

            return query;
        }
    }
}
